package com.superteam.zzl.utils;

import android.app.Application;
import android.content.Context;
import com.superteam.zzl.gen.DaoMaster;
import com.superteam.zzl.gen.DaoSession;

/**
 * Created by zhang on 2017/1/6.
 */

/**
 * 实例化greenDAO所需要的几个关键对象，DaoMaster，DaoSession
 */
public class GreenDaoManager {
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private static volatile GreenDaoManager mInstance = null;

    /**
     * 单例模式
     */
    private GreenDaoManager(Context context){
        if (mInstance == null) {
            DaoMaster.DevOpenHelper devOpenHelper = new
                    DaoMaster.DevOpenHelper(context,"ZZL.db");
            mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
            mDaoSession = mDaoMaster.newSession();
        }
    }
    public static GreenDaoManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (GreenDaoManager.class) {
                    if (mInstance == null) {
                        mInstance = new GreenDaoManager(context);
                }
            }
        }
        return mInstance;
    }
    public DaoMaster getMaster() {
        return mDaoMaster;
    }
    public DaoSession getSession() {
        return mDaoSession;
    }
    public DaoSession getNewSession() {
        mDaoSession = mDaoMaster.newSession();
        return mDaoSession;
    }

}


/**
 * *******************************使   用**********************************
 *
 * 数据库的增、删、改、查
 以User实体为例:
 首先获得UserDao的对象
 UserDao userDao = GreenDaoManager.getInstance(参数列表).getNewSession().getUserDao();

 增：
 User user = new User(null, name, age, studentId);
 userDao.insert(user);

 insert(T entity)       当指定主键在表中存在时会发生异常
 insertOrReplace(T entity)      当指定主键在表中存在时会覆盖数据
 insertInTx(Iterable<T> entities)    批量插入数据

 删：
 User user = new User(null, name, age, studentId);
 userDao.delete(user)

 delete(T entity)       删除数据
 deleteByKey(K key)     指定主键删除数据
 deleteInTx(Iterable<T> entities)      批量删除数据
 deleteByKeyInTx(Iterable<K> keys)      批量按数据删除数据
 deleteAll()    删除所有数据

 改：
 User user = new User(id, name, age, studentId);
 userDao.update(user);

 update(T entity)       修改数据，主键需相同
 updateInTx(Iterable<T> entities)      批量更新数据


 查：
 userDao.load(id)

 load(K key)    根据id查找数据
 loadByRowId(long rowId)    根据行号查找数据
 loadAll()      查找全部数据

 */
